const Client = require('../../mongooses/oauth/Client')
const uniqueString = require('unique-string');

class OauthClientController {
    constructor () {

    }
    // GET 索引列表
    async index (ctx, next) {
        let clients = await Client.find({});
        ctx.body = {
            ret: 0,
            msg: 'OK',
            data: clients
        }
    }
    // GET 创建显示表单
    async create (ctx, next) {
        ctx.body = 'create';
    }
    //POST 保存创建的数据
    async store (ctx, next) {
        let data = {
            user_id: ctx.request.body.user_id,
            name: ctx.request.body.name,
            secret: uniqueString(),
            redirect: ctx.request.body.redirect,
            personal_access_client: ctx.request.body.personal_access_client,
            password_client: ctx.request.body.password_client
        }
        let client = await Client.create(data)
        ctx.body = {
            ret: 0,
            msg: 'OK',
            data: client
        }
    }
    //GET 显示对应id的内容
    async show (ctx, next) {
        let id = ctx.request.body.id

        let client = await Client.findById(id)

        ctx.body = {
            ret: 0,
            msg: 'OK',
            data: client
        } 
    }
    //GET 编辑（显示表单）
    async edit (ctx, next) {
        ctx.body = 'index';
    }
    // PUT/PATCH保存
    async save (ctx, next) {
        let id = ctx.request.body.id
        let data = {
            name: ctx.request.body.name,
            redirect_uri: ctx.request.body.redirect_uri
        }
        let client = await Client.findByIdAndUpdate({ '_id': id }, { $set: data })
        ctx.body = {
            ret: 0,
            msg: 'OK',
            data: res
        }  
    }
    // GET 删除
    async destroy (ctx, next) {
        let id = ctx.request.body.id
        let res = await Client.findByIdAndRemove({'_id': id})
        ctx.body = {
            ret: 0,
            msg: 'OK',
            data: res
        } 
    }
}
module.exports = new OauthClientController()